using System;
using System.Xml;

namespace Elev.Core.Utility
{
    internal class XmlHelper
    {
        static public XmlNode ReplaceNode(XmlNode nodeToRemove, XmlNode nodeToInsert)
        {
            XmlNode parent = nodeToRemove.ParentNode;
            parent.RemoveChild(nodeToRemove);
            return ImportNode(nodeToInsert, parent);
        }

        static public void CreateElements(XmlNode parent, params string[] elementNames)
        {
            foreach (string n in elementNames) CreateElement(parent, n);
        }

        static public XmlNode CreateElement(XmlNode parent, string elementName)
        {
            return CreateElement(parent, elementName, null);
        }

        static public XmlNode CreateElement(XmlNode parent, string elementName, string innerText)
        {
            XmlDocument ownerDoc = (parent is XmlDocument ? (XmlDocument)parent : parent.OwnerDocument);
            if (ownerDoc == null)
            {
                throw new ArgumentException("The supplied node neither has an OwnerDocument nor is it an XmlDocument.", "parent");
            }
            XmlNode newChild = ownerDoc.CreateElement(elementName);
            if (innerText != null)
            {
                newChild.InnerText = innerText;
            }
            return parent.AppendChild(newChild);
        }

        static public void AppendAttribute(XmlNode oParent, string sAttributeName, string sInnerText)
        {
            XmlDocument ownerDoc = (oParent is XmlDocument ? (XmlDocument)oParent : oParent.OwnerDocument);
            if (ownerDoc == null)
            {
                throw new ArgumentException("The supplied node neither has an OwnerDocument nor is it an XmlDocument.", "parent");
            }

            XmlAttribute oAttribute = ownerDoc.CreateAttribute(sAttributeName);
            oAttribute.InnerText = sInnerText;

            oParent.Attributes.Append(oAttribute);
        }

        static public XmlNode ImportNode(XmlNode sourceNode, XmlNode importingParentNode)
        {
            XmlDocument importingDoc = (importingParentNode is XmlDocument ? (XmlDocument)importingParentNode : importingParentNode.OwnerDocument);
            if (importingDoc == null)
            {
                throw new ArgumentException("The supplied node neither has an OwnerDocument nor is it an XmlDocument.", "importingParentNode");
            }
            XmlNode clone = importingDoc.ImportNode(sourceNode, true);
            importingParentNode.AppendChild(clone);
            return clone;
        }
    }
}
